package org.elsfs.cloud.common.mybatis.ext.sql.support.condition;



import java.util.List;
import java.util.stream.Collectors;

/**
 * 聚合条件
 *
 */
public class CompositeConditionItem implements ConditionItem {

    /**
     * 条件列表
     */
    private final List<ConditionItem> conditions;

    public CompositeConditionItem(List<ConditionItem> conditions) {
        this.conditions = conditions;
    }

    /**
     * 构建SQL片段
     *
     * @return SQL片段
     */
    @Override
    public String buildSqlFragment() {
        if (this.conditions.isEmpty()) {
            return "";
        }

        String conditionSql = this.conditions.stream()
            .map(ConditionItem::buildSqlFragment)
            .collect(Collectors.joining(" "));

        if (this.conditions.size() == 1) {
            return ConditionItem.stripHeaderKeyword(conditionSql);
        }

        return String.format(
            "(%s)",
            ConditionItem.stripHeaderKeyword(conditionSql)
        );
    }
}
